﻿
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.IO;  

using Wind.MultimediaStation.WebService.Entity;
using Wind.Utils;
using Wind.Utils.Web;
using Wind.SecureWeb;

namespace Wind.MultimediaStation.WebService
{
    public class MultimediaStationHandler : BasePage,IHttpHandler
    {
        static IMultimediaStationBusiness oBusiness = new MultimediaStationBusiness();
        public MultimediaStationHandler()
        { }


        int _channelID = 0;//频道ID
        int _playOrderID = 0;//串联单ID
        string _cityName = "shanghai";


        /// <summary>
        /// 入口点
        /// </summary>
        /// <param name="context"></param>
        public new void ProcessRequest(HttpContext context)
        {
            try
            {
                string sWriteXml = string.Empty;
               sWriteXml = ResponseXmlContent(context.Request.QueryString["type"], context);              
               context.Response.Charset = "utf-8";
               context.Response.ContentType = "text/xml";
               context.Response.Write(sWriteXml);
            }
            catch (Exception ex)
            {
                LogHelper.Write("MultimediaStationHandler ProcessRequest Exception:", ex);
            }
        }

        public bool IsReusable
        {
            get { return false; }
        }

        /// <summary>
        /// 根据不同函数类型输出不同XML文件流,类型为别为 
        /// 获取频道列表 type=channel
        /// 根据频道获取串联单列表 type=playorder&id= (id为频道ID)
        /// 根据串联单ID获取节目列表 type=act&id=  (id为串联单ID)
        /// 检查是否有新频道 type=new
        /// </summary>
        /// <param name="functionType">函数类型，通过URL参数传入</param>
        /// <param name="context">上下文</param>
        /// <returns></returns>
        private string ResponseXmlContent(string functionType, HttpContext context)
        {
            try
            {
                string value = string.Empty;
                string key = functionType.ToLower();
                string keyValue = string.Empty;
                string reqID = context.Request.QueryString["id"];
                switch (key)
                {
                    case "channel":
                        keyValue = key;
                        if (CacheHelper.GetCache(keyValue) == null)
                        { 
                            value = Serializer(typeof(List<OChannelInfo>), oBusiness.GetChannelList());
                            SetCache(keyValue, value);
                        }
                        value = CacheHelper.GetCache(keyValue) as string;
                        break;
                    case "playorder":
                        keyValue = key + reqID;
                        if (CacheHelper.GetCache(keyValue) == null)
                        {
                            _channelID = int.Parse(reqID);
                            value = Serializer(typeof(List<OPlayOrderInfo>), oBusiness.GetPlayOrderListByChannelID(_channelID));
                            SetCache(keyValue, value);
                        }
                        value = CacheHelper.GetCache(keyValue) as string;
                        break;
                    case "act":
                        keyValue = key + reqID;
                        if (CacheHelper.GetCache(keyValue) == null)
                        {
                            _playOrderID = int.Parse(reqID);
                            value = Serializer(typeof(List<OActInfo>), oBusiness.GetActInfoListByID(_playOrderID));
                            SetCache(keyValue, value);
                        }
                        value = CacheHelper.GetCache(keyValue) as string;                 
                        break;
                    case "new":
                        keyValue = key + reqID;
                        if (CacheHelper.GetCache(keyValue) == null)
                        {
                            value = oBusiness.HasNewChannnel().ToString();
                            SetCache(keyValue, value);
                        }
                        value = CacheHelper.GetCache(keyValue) as string;
                        break;
                    case "weather":
                        keyValue = key + reqID;
                        if (CacheHelper.GetCache(keyValue) == null)
                        {
                            _cityName = reqID;
                            value = Serializer(typeof(OWeather), oBusiness.GetWeatherbyCityName(_cityName));
                            SetCache(keyValue, value);
                        }
                        value = CacheHelper.GetCache(keyValue) as string;
                        break;
                    case "log":                       
                        oBusiness.WriterErrorLog(context.Server.UrlDecode(context.Request["message"]));
                        value = null;
                        break;
                    default:
                        break;
                }
                return value;
            }
            catch {
                return string.Empty;
            }
        }

        private string GetData(string key, string value)
        {
            if (CacheHelper.GetCache(key) == null)
            {
                SetCache(key, value);                
            }
            return CacheHelper.GetCache(key) as string;
        }
        private void SetCache(string key, object obj)
        {
            CacheHelper.SetCache(
              key,　　　//需要添加到Cache中的键
              obj,　　　 //对应的值　　　　　　　　　　　　　　　　　
              DateTime.Now.AddSeconds(Convert.ToDouble(Wind.Framework.ConfigManager.GetAppSettingValue("CacheTime", "20"))),//固定缓存时间
              new System.Web.Caching.CacheItemRemovedCallback(OnMoveCacheBack)//移除时调用的回调函数
          );
        }
        /// <summary>
        /// 当缓存过期后的策略
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="reason"></param>
        protected void OnMoveCacheBack(string key, object obj, System.Web.Caching.CacheItemRemovedReason reason)
        {
            if (CacheHelper.GetCache(key) != null)
            {
                CacheHelper.RemoveCache(key);
            }
            //SetCache(key, obj);
        }
        #region 序列化XML文件
        /// <summary>   
        /// 序列化XML文件   
        /// </summary>   
        /// <param name="type">类型</param>   
        /// <param name="obj">对象</param>   
        /// <returns></returns>   
        public static string Serializer(Type type, object obj)
        {
            MemoryStream Stream = new MemoryStream();
            //创建序列化对象   
            XmlSerializer xml = new XmlSerializer(type);

            try
            {
                //序列化对象   
                xml.Serialize(Stream, obj);
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            Stream.Position = 0;
            StreamReader sr = new StreamReader(Stream);
            string str = sr.ReadToEnd();

            return str;
        }
        #endregion
    }
}
